package com.sservice.web.controller.admin;

import com.sservice.common.Constants;
import com.sservice.common.SameUrlData;
import com.sservice.model.dao.IClienteleDao;
import com.sservice.model.vo.ClienteleVo;
import com.sservice.service.service.IClienteleService;
import com.sservice.service.service.ISysLogService;
import com.sservice.base.entity.dto.BaseResult;
import com.sservice.base.entity.dto.ListResult;
import com.sservice.base.entity.dto.Pagination;
import com.sservice.model.entity.Clientele;
import com.sservice.banfu.e.SalePerson;
import com.sservice.urp.entity.User;
import com.sservice.web.log.Action;
import com.github.stuxuhai.jpinyin.PinyinException;
import com.github.stuxuhai.jpinyin.PinyinFormat;
import com.github.stuxuhai.jpinyin.PinyinHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin/clientele")
public class ClienteleController {
    @Autowired
    IClienteleService dataService;
    @Autowired
    IClienteleDao dataDao;
    @Autowired
    ISysLogService logService;
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 创建
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/get", method = RequestMethod.GET)
    public BaseResult<Clientele> get(Clientele arg) {
        Clientele service_res = dataService.selectByPrimaryKey(arg.getId());
        BaseResult<Clientele> res = new BaseResult<Clientele>(true, service_res);
        return res;
    }

    /***
     * 替换某一个客户整个系统的UnitCode
     * @param arg
     * @return
     */
    @SameUrlData
    @ResponseBody
    @RequestMapping(value = "/replace/{unitCode}/{id}/{comName}", method = RequestMethod.GET)
    public BaseResult<Clientele> replace(Clientele arg, HttpSession session) {
        User user = (User) session.getAttribute(Constants.USER);
        if (user.getId() != 1) {
            return new BaseResult(false, "非超级管理员用户，不能进行此操作!", 403);
        }
        //comName old

        Clientele c = dataService.selectByPrimaryKey(arg.getId());
        if (c != null && c.getUnitCode().equals(arg.getComName())) {
            Map map = new HashMap();
            map.put("old", arg.getComName());
            map.put("newer", arg.getUnitCode());
            dataDao.replaceUnitCode(map);
            return new BaseResult(true, "操作成功");
        } else {
            return new BaseResult(false, "参数有误", 403);
        }
    }

    /**
     * create
     *
     * @param arg
     * @return
     */
    @ResponseBody
    @SameUrlData
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public BaseResult<Integer> insert(Clientele arg, HttpSession session) {
        SalePerson sale = (SalePerson) session.getAttribute("current");
        arg.setSalesId(String.valueOf(sale.getId()));
        int service_res = dataService.insertSelective(arg);
        BaseResult<Integer> res = new BaseResult<Integer>(true, service_res);
        return res;
    }

    /***
     * 供应商审核
     * @param arg
     * @param request
     * @return
     */
    @ResponseBody
    @SameUrlData
    @RequestMapping(value = "/provider/{remark}/{id}/{reason}", method = RequestMethod.POST)
    public BaseResult<Integer> provider(Clientele arg, HttpServletRequest request) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        Clientele cl = new Clientele();
        if ("allow".equals(arg.getRemark())) {
            cl.setSupplierCheckStatus("1");
            cl.setRemitInfoBack(arg.getRemitInfoBack());
            logService.log("供应商审核通过", request, arg.getId(), Action.clienteleType);
        } else {
            cl.setSupplierCheckStatus("2");
            logService.log("供应商审核拒绝", request, arg.getId(), Action.clienteleType);
        }
        cl.setId(arg.getId());
        cl.setSupplierCheckReason(arg.getReason());
        int service_res = dataService.updateByPrimaryKeySelective(cl);
        BaseResult<Integer> res = new BaseResult<Integer>(true, service_res);
        return res;
    }

    /**
     * update
     *
     * @param arg
     * @return
     */
    @ResponseBody
    @SameUrlData
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public BaseResult<Integer> update(Clientele arg) {
        int service_res = dataService.updateByPrimaryKeySelective(arg);
        BaseResult<Integer> res = new BaseResult<Integer>(true, service_res);
        return res;
    }

    /**
     * updateSope
     *
     * @param arg
     * @return
     */
    @ResponseBody
    @SameUrlData
    @RequestMapping(value = "/updateSope", method = RequestMethod.POST)
    public BaseResult<Integer> updateSope(Clientele arg, HttpServletRequest request) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        String remark = arg.getRemark();
        String address = arg.getAddress();
        arg.setRemark(null);
        arg.setAddress(null);
        int service_res = dataService.updateByPrimaryKeySelective(arg);
        if (service_res > 0) {
            logService.log("更新危险化学品经营许可证／安全生产许可证经营范围：" + remark + ",更新易制毒备案经营范围：" + address, request, arg.getId(), Action.clienteleType);
        }


        BaseResult<Integer> res = new BaseResult<Integer>(true, service_res);
        return res;
    }

    /***
     * 分页查询
     * @param arg
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/query", method = RequestMethod.GET)
    public ListResult<Clientele> query(ClienteleVo arg) {
        List<Clientele> list = dataService.queryByPage(arg);
        int total = dataService.queryCount(arg);
        Pagination page = new Pagination(arg.getPage(), total, arg.getSize());
        ListResult<Clientele> res = new ListResult(true, list);
        res.setPage(page);
        return res;
    }

    /**
     * 供应商查询
     *
     * @param arg
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/querySupplier", method = RequestMethod.GET)
    public ListResult<Clientele> supplier(ClienteleVo arg) {
        List<Clientele> list = dataService.querySupplierByPage(arg);
        int total = dataService.querySupplierCount(arg);
        Pagination page = new Pagination(arg.getPage(), total, arg.getSize());
        ListResult<Clientele> res = new ListResult(true, list);
        res.setPage(page);
        return res;
    }

    @ResponseBody
    @RequestMapping(value = "/queryPinyin", method = RequestMethod.GET)
    public ListResult<ClienteleVo> queryPinyin(ClienteleVo arg) throws PinyinException {
        List<Clientele> list = dataService.queryByPage(arg);
        List<ClienteleVo> vo = new ArrayList<ClienteleVo>();
        for (Clientele ele :
                list) {
            ClienteleVo cv = new ClienteleVo();
            cv.setComName(ele.getComName());
            cv.setPerson(ele.getPerson());
            cv.setPhone(ele.getPhone());
            cv.setUnitCode(ele.getUnitCode());
            cv.setId(ele.getId());
            cv.setPinyin(PinyinHelper.convertToPinyinString(cv.getComName(), "", PinyinFormat.WITHOUT_TONE));
            vo.add(cv);
        }

        int total = dataService.queryCount(arg);
        Pagination page = new Pagination(arg.getPage(), total, arg.getSize());
        ListResult<ClienteleVo> res = new ListResult(true, vo);
        res.setPage(page);
        return res;
    }


    @ResponseBody
    @RequestMapping(value = "/queryAuto", method = RequestMethod.GET)
    public ListResult<Clientele> queryAuto(ClienteleVo arg) {
        List<Clientele> list = dataService.queryByPage(arg);
        int total = dataService.queryCount(arg);
        Pagination page = new Pagination(arg.getPage(), total, arg.getSize());
        ListResult<Clientele> res = new ListResult(true, list);
        res.setPage(page);
        res.setTotal(total);
        return res;
    }

    @ResponseBody
    @RequestMapping(value = "/querySaleClientele", method = RequestMethod.GET)
    public BaseResult<Clientele> querySaleClientele(ClienteleVo arg) {
        List<Clientele> list = dataService.queryMyClientele(arg);

        BaseResult<Clientele> res = new ListResult(true, list);
        return res;
    }
}
